package io.shdxhl.simplerpc.code.netty.strategy.impl;

import io.shdxhl.simplerpc.client.provider.ServiceProvider;
import io.shdxhl.simplerpc.code.annotation.SimpleLoadBalance;
import io.shdxhl.simplerpc.code.netty.strategy.LoadBalanceStrategy;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡
 */
@SimpleLoadBalance(strategy = "polling")
public class PollingLoadBalanceStrategy implements LoadBalanceStrategy {
    private AtomicInteger nextCounter = new AtomicInteger(0);
    @Override
    public ServiceProvider select(List<ServiceProvider> serviceProviders) {
        int index = incrementAndGet(serviceProviders.size());
        return serviceProviders.get(index);
    }

    private int incrementAndGet(int size) {
        for (;;){
            int currentIndex = nextCounter.get();
            int nextIndex = (currentIndex + 1) % size;
            if(nextCounter.compareAndSet(currentIndex, nextIndex)){
                return currentIndex;
            }
        }
    }
}
